﻿using UnityEngine;
using System.Collections;
using Asset.Script.Core;
using System;
using System.IO;

namespace Asset.Script.Update
{
    
    public class CheckVersion : Singleton<CheckVersion>
    {
        public const string Version = "1.1.6";//外网正式服版本 12 //--"2.0.86"内网测试服版本
		public const bool iosPending = false;
        
        
        public delegate void CallBack(bool isSucess);
        public delegate void GetBack(string code);
        public delegate void CheckCallBack(CheckState state);

        public enum CheckState
        {
            /// <summary>
            /// 
            /// </summary>
            Fail,
            /// <summary>
            ///
            /// </summary>
            NoUpdate,
            /// <summary>
            ///
            /// </summary>
            NeedUpdate,
            /// <summary>
            ///
            /// </summary>
            NeedResetup,
        }

        public void Check(MonoBehaviour mono, CheckCallBack callback)
        {
            string url = UpdateConfig.Instance.ResServerRoot + @"/" + UpdateConfig.Instance.VersionFileName+ "?t=" + System.DateTime.UtcNow.ToFileTimeUtc().ToString();
            mono.StartCoroutine(GetVersionCode(url, (code) =>
            {
                if (string.IsNullOrEmpty(code))//获取版本号为空
                {
                    callback(CheckState.Fail);
                    return;
                }
                string localCode = LocalVersion();
                if (string.IsNullOrEmpty(localCode)) //本地没有版本号文件，提示需要更新
                {
                    callback(CheckState.NeedUpdate);
                    return;
                }
                if (code != localCode)
                {
                    string[] subCodes = code.Split('.');
                    string[] StaticSubCodes = Version.Split('.');
                    if (StaticSubCodes[0] != subCodes[0])
                    {
                        callback(CheckState.NeedResetup);
                    }
                    else
                    {
                        callback(CheckState.NeedUpdate);
                    }
                }
                else
                {
                    callback(CheckState.NoUpdate);
                }
            }));
        }


        public IEnumerator GetVersionCode(string url, GetBack callBack)
        {
            WWW request = new WWW(url);
           
            int count = 0;
            bool isGetText = true;
            while (!request.isDone)
            {
                yield return new WaitForSeconds(0.1f);
                count++;
                if (count >= 40)
                {
                    isGetText = false;
                    break;
                }
            }

            if (isGetText)
            {
                if (!string.IsNullOrEmpty(request.error))
                {
                    Debug.Log("request.error:" + request.error.ToString());
                    isGetText = false;
                }
                else
                {
                    Debug.Log("request:" + request.text.ToString());
                }
            }

            if (!isGetText)
            {
                callBack(null);
                request.Dispose();
                yield break;
            }
            else
            {
                string code = request.text;
                callBack(code);
                request.Dispose();
                yield break;
            }
        }

        public string LocalVersion()
        {
            string code = null;
            if(File.Exists(UpdateConfig.Instance.LocalVersionCodePath))
            {
                using (StreamReader reader = File.OpenText(UpdateConfig.Instance.LocalVersionCodePath))
                {
                    code = reader.ReadToEnd();
                }
            }
            return code;
        }

        public bool LocaliOSPendingState()
        {
            bool iosPending = false;

#if UNITY_EDITOR
            iosPending = false;
#elif UNITY_ANDROID
		    iosPending = false;
#elif UNITY_IPHONE
            if (File.Exists(UpdateConfig.Instance.LocaliOSPendingFilePath))
            {
                using (StreamReader reader = File.OpenText(UpdateConfig.Instance.LocaliOSPendingFilePath))
                {
                    string code = reader.ReadToEnd();
                    iosPending = bool.Parse(code);
                }
            }
            else
            {
                iosPending = false;
            }
#endif
            return iosPending;
        }

        public bool LocalQQPendingState()
        {
            bool qqPending = false;

#if UNITY_EDITOR
            qqPending = false;
#elif UNITY_ANDROID
		     if (File.Exists(UpdateConfig.Instance.LocalQQPendingFilePath))
            {
                using (StreamReader reader = File.OpenText(UpdateConfig.Instance.LocalQQPendingFilePath))
                {
                    string code = reader.ReadToEnd();
                    qqPending = bool.Parse(code);
                }
            }
            else
            {
                qqPending = false;
            }
#elif UNITY_IPHONE
            qqPending = false;
#endif
            return qqPending;
        }


        public IEnumerator GetMD5List(string url, GetBack callBack)
        {
            WWW request = new WWW(url + "?t=" + System.DateTime.UtcNow.ToFileTimeUtc().ToString());
            yield return request;
            if (!string.IsNullOrEmpty(request.error))
            {
                Debug.LogError("获取MD5列表异常:" + request.error);
                callBack(null);
                yield break;
            }
            string md5list = request.text;
            callBack(md5list);
        }
    }
}
